/*
 * Copyright (C) 2013 ePapyrus, Inc. All rights reserved.
 *
 * This file is part of the PlugPDF Android project.
 */

/*
 * AnnotSettingMenu.java
 * 
 * Version:
 *       id
 *       
 * Revision:
 *      logs
 */

package com.epapyrus.plugpdf;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.GradientDrawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;

import com.epapyrus.plugpdf.core.annotation.tool.AnnotSetting;
import com.epapyrus.plugpdf.core.annotation.tool.BaseAnnotTool.AnnotToolType;

import java.util.regex.Pattern;

/**
 * Setups the Annotation menu, creates and shows the annotation pop-up window.
 *  
 * @author ePapyrus
 * @see <a href="http://www.plugpdf.com">http://www.plugpdf.com</a>
 */
public class AnnotSettingMenu {
	private Context mContext;
	private LayoutInflater mInflater;
	private PopupWindow mPopupWindow;
	private HSVColorWheel mColorWheel;
	private EditText mEditLineColor;

	private static final String PX = "px";
	private static final String PERCENT = "%";
	private AnnotToolType mAnnotType;
	private ImageView mAnnotSettingColorPickerButton;

	GridView gridView;

	/**
	 * Constructor that assigns the context and initializes the {@link LayoutInflater}.
	 * 
	 * @param context {@link Context} instance
	 */
	public AnnotSettingMenu(Context context) {
		mContext = context;
		mInflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	/**
	 * Given an annotation type it creates the annotation pop-up window.
	 *
	 * @param type Annotation tool type
	 */
	@SuppressLint("InflateParams")
	private void createPopupWindow(AnnotToolType type) {
		final AnnotSetting setting = AnnotSetting.instance();

		View menuView = mInflater.inflate(R.layout.annot_setting, null);

		mPopupWindow = new PopupWindow(menuView, LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT, true);
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

		mColorWheel = (HSVColorWheel) menuView.findViewById(R.id.color_picker);
		mColorWheel.setColor(setting.getColorPickerLineColor() - 0xff000000);

		//mAnnotSettingColorPickerButton = (ImageView) ((Activity)mContext).findViewById(R.id.current_color_picker);

		mEditLineColor = (EditText) menuView.findViewById(R.id.annot_line_color);
		mEditLineColor.setText( Integer.toHexString(setting.getLineColor(mAnnotType)));
		mEditLineColor.setTextColor(0xff000000 +  setting.getLineColor(mAnnotType));
		// line color
		int[] colorSet = { 0x000000, 0x171717, 0xF6402C, 0xFFC100, 0xFFEC16, 0x88C440, 0x00A6F6, 0x3D4DB7, 0x6633B9, 0x9D9D9D };

		gridView = (GridView)menuView.findViewById(R.id.annot_line_color_value);
		final ColorPickerAdapter colorPickerAdapter = new ColorPickerAdapter(mContext, colorSet);
		gridView.setAdapter(colorPickerAdapter);
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				setting.setLineColor((int) colorPickerAdapter.getItem(position), mAnnotType);
				mEditLineColor.setText(Integer.toHexString(setting.getLineColor(mAnnotType) & 0xffffff));
			}
		});

		mColorWheel.setListener( new OnColorSelectedListener() {
			public void colorSelected(Integer color) {
				setting.setColorPickerLineColor(color);
				setting.setLineColor(color & 0xffffff, mAnnotType);
				mEditLineColor.setText(Integer.toHexString(setting.getLineColor(mAnnotType)));
				gridView.invalidateViews();
			}
		} );

		InputFilter[] hexFilterWithMaxLine = new InputFilter[2];
		hexFilterWithMaxLine[0] = new InputFilter.LengthFilter(6);
		hexFilterWithMaxLine[1] = new InputFilter() {
			@Override
			public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
				Pattern pattern = Pattern.compile("^[a-fA-F0-9]+$");
				if(!pattern.matcher(source).matches()) return "";
				return null;
			}
		};

		mEditLineColor.setFilters(hexFilterWithMaxLine);
		mEditLineColor.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				String colorValue = new String(s.toString());
				while (colorValue.length() < 6) {
					colorValue = "0" + colorValue;
				}

				mEditLineColor.setTextColor(Color.parseColor("#" + colorValue));

				if(s.toString().equals("")) {
					setting.setLineColor(0x000000, mAnnotType);
				} else {
					setting.setLineColor(Integer.parseInt(s.toString(), 16), mAnnotType);
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
				((GradientDrawable) mAnnotSettingColorPickerButton.getBackground()).setColor(0xff000000 + AnnotSetting.instance().getLineColor(mAnnotType));
			}
		});

		// fill color
//		Spinner fillColorSpinner = (Spinner) menuView
//				.findViewById(R.id.annot_fill_color_value);
//		fillColorSpinner.setSelection(getSpinnerPos(setting.getFillColor(mAnnotType)));
//		fillColorSpinner
//				.setOnItemSelectedListener(new OnItemSelectedListener() {
//					@Override
//					public void onItemSelected(AdapterView<?> parent,
//							View view, int position, long id) {
//						setting.setFillColor(getColorFromSpinner(position), mAnnotType);
//					}
//
//					@Override
//					public void onNothingSelected(AdapterView<?> parent) {
//					}
//				});
		
		// line opacity
		final TextView lineOpacityValueDisplay = (TextView) menuView
				.findViewById(R.id.annot_opacity_value_display);
		lineOpacityValueDisplay.setText(Integer.toString((int) (AnnotSetting
				.instance().getOpacity(mAnnotType) / 255.0f * 100)) + PERCENT);

		SeekBar lineOpacityValue = (SeekBar) menuView
				.findViewById(R.id.annot_opacity_value);
		lineOpacityValue.setProgress(setting.getOpacity(mAnnotType));
		lineOpacityValue
				.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

					@Override
					public void onProgressChanged(SeekBar seekBar,
							int progress, boolean fromUser) {
						lineOpacityValueDisplay.setText(Integer
								.toString((int) (progress / 255.0f * 100))
								+ PERCENT);
					}

					@Override
					public void onStartTrackingTouch(SeekBar seekBar) {
					}

					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {
						setting.setOpacity(seekBar.getProgress(), mAnnotType);
						lineOpacityValueDisplay.setText(Integer
								.toString((int) (setting.getOpacity(mAnnotType) / 255.0f * 100))
								+ PERCENT);
					}
				});

		// line width
		final TextView lineWidthValueDisplay = (TextView) menuView
				.findViewById(R.id.annot_line_width_value_display);
		lineWidthValueDisplay.setText(Integer.toString(setting.getLineWidth(mAnnotType))
				+ PX);

		SeekBar lineWidthValue = (SeekBar) menuView
				.findViewById(R.id.annot_line_width_value);
		lineWidthValue.setProgress(setting.getLineWidth(mAnnotType));
		lineWidthValue
				.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

					@Override
					public void onProgressChanged(SeekBar seekBar,
							int progress, boolean fromUser) {
						lineWidthValueDisplay.setText(Integer
								.toString(progress) + PX);
					}

					@Override
					public void onStartTrackingTouch(SeekBar seekBar) {
					}

					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {
						setting.setLineWidth(seekBar.getProgress(), mAnnotType);
						lineWidthValueDisplay.setText(Integer.toString(setting
								.getLineWidth(mAnnotType)) + PX);
					}
				});

		// line straight
		final CheckBox straight = (CheckBox) menuView
				.findViewById(R.id.annot_line_straight);
		straight.setChecked(setting.getInkLineStraight());
		straight.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				straight.setChecked(isChecked);
				setting.setInkLineStraight(isChecked);
			}
		});
		
		// line squiggly
		final CheckBox squiggly = (CheckBox) menuView
				.findViewById(R.id.annot_line_squiggly);
		squiggly.setChecked(setting.isSquiggly());
		squiggly.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				squiggly.setChecked(isChecked);
				setting.setSquiggly(isChecked);
			}
		});

		switch (mAnnotType) {
		case INK:
			menuView.findViewById(R.id.annot_fill_color_title).setVisibility(View.GONE);
			menuView.findViewById(R.id.annot_fill_color_value).setVisibility(View.GONE);
			menuView.findViewById(R.id.annot_line_squiggly).setVisibility(View.GONE);
			break;
		case STRIKEOUT:
		case HIGHLIGHT:
			menuView.findViewById(R.id.annot_line_squiggly).setVisibility(View.GONE);
		case UNDERLINE:
			menuView.findViewById(R.id.annot_line_straight).setVisibility(View.GONE);
			menuView.findViewById(R.id.annot_line_opacity_layout).setVisibility(View.GONE);
			menuView.findViewById(R.id.annot_line_width_layout).setVisibility(View.GONE);
			break;
		case SQUARE:
		case CIRCLE:
			menuView.findViewById(R.id.annot_line_straight).setVisibility(View.GONE);
			menuView.findViewById(R.id.annot_line_squiggly).setVisibility(View.GONE);
			//((TextView) menuView.findViewById(R.id.annot_line_color_title)).setText("Line Color : # ");
		default:
			menuView.findViewById(R.id.annot_fill_color_title).setVisibility(View.GONE);
			menuView.findViewById(R.id.annot_fill_color_value).setVisibility(View.GONE);
			break;
		}
	}

	/**
	 * Given both the annotation type and the position of the annotation pop-up, it creates and shows
	 * the annotation tool's pop-up.
	 *
	 * @param anchor  A parent {@link View} to get Window token from
	 * @param x       The popup's x location offset
	 * @param y       The popup's y location offset
	 * @param type    Annotation tool type
	 */
	public synchronized void show(final View anchor, final int x, final int y, AnnotToolType type) {

		mAnnotType = type;
		//mAnnotType = AnnotToolType.CIRCLE;
		createPopupWindow(mAnnotType);
		
		mPopupWindow.showAtLocation(anchor, Gravity.CENTER, x, y);
	}

	/**
	 * Closes the annotation pop up.
	 */
	public synchronized void close() {
		if (mPopupWindow != null) {
			mPopupWindow.dismiss();
		}
	}

	public PopupWindow getPopupWindow(){
		return mPopupWindow;
	}
}
